#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : jmp_file.py
@Author  : Link
@Time    : 2022/3/27 17:04
@Mark    :
"""
import os
import time
from string import Template
from typing import List


class JmpyFile:
    """
    JMP的文件操作接口
    """

    @staticmethod
    def jPrintScript(*jmp_script):
        script = "\n".join(jmp_script)
        print(script)
        time.sleep(0.1)

    @staticmethod
    def jExecuteScript(*jmp_script, scrip_name="script.jsl"):
        new_script = []
        for each in jmp_script:
            for line in each.split('\n'):
                line = line.strip()
                if line == "":
                    continue
                new_script.append(line)
        script = "\n".join(new_script)
        with open(scrip_name, "w", encoding="utf-8") as f:
            f.write(script)
        os.startfile(scrip_name)

    @staticmethod
    def jRunScript(scrip_name):
        os.startfile(scrip_name)

    @staticmethod
    def jOpenPng(filepath: str) -> str:
        """
        读取图片
        :param filepath:
        :return:
        """
        return Template(
            """
Open( "$filepath");
            """
        ).substitute(**locals())

    @staticmethod
    def jLoadPng(filepath: str, pb_name: str = "pb") -> str:
        """
        读取图片
        :param filepath:
        :param pb_name:
        :return:
        """
        return Template(
            """
$pb_name = Picture Box(Open( "$filepath", png));
            """
        ).substitute(**locals())

    @staticmethod
    def jLoadJpg(filepath: str, pb_name: str = "pb") -> str:
        """
        读取图片
        :param filepath:
        :param pb_name:
        :return:
        """
        return Template(
            """
$pb_name = Picture Box(Open( "$filepath", jpg));
            """
        ).substitute(**locals())

    @staticmethod
    def jLoadCsv(
            filepath: str, dt_name: str = "dt", in_vis: bool = True,
            row_head:int = 1, row_start:int = 2, col_start:int = 1
    ) -> str:
        """
        读取CSV文件
        返回DT
        :param filepath:
        :param dt_name:
        :param in_vis: 是否显示DataTable, 默认隐藏
        :param row_head: 默认表头行
        :param row_start: 默认数据开始行
        :param col_start: 默认数据开始列
        :return:
        """
        in_vis="Invisible," if in_vis else ""
        return Template("""
$dt_name = Open("$filepath", $in_vis
Import Settings(
    Labels( $row_head ),
    Column Names Start( $col_start ),
    Data Starts( $row_start ),
));
        """).substitute(**locals())

    @staticmethod
    def jCloseAll():
        """
        用在直接关闭app上面比较方便, 缺点是会把所有的都给杀了
        """
        return """
Close All( Data Tables, NoSave );
Close All( Reports, NoSave );
Close All( Journals, NoSave );
        """

    @staticmethod
    def jSaveInteractiveHtml(html_path, rbiv: str = "rbiv"):
        return Template("""
$rbiv << Save Interactive HTML( "$html_path" );
Run Program(
    Executable( "CMD.EXE"/*path probably not needed*/ ),
    Options( {"/c","$html_path" } ),
);
$rbiv << Close Window;
        """).substitute(**locals())

    @staticmethod
    def jSaveHtml(html_path, rbiv: str = "rbiv") -> str:
        return Template("""
$rbiv << Save HTML( "$html_path" );
Run Program(
    Executable( "CMD.EXE"/*path probably not needed*/ ),
    Options( {"/c","$html_path" } ),
);
$rbiv << Close Window;
        """).substitute(**locals())

    @staticmethod
    def jSavePng(png_path, rbiv: str = "rbiv") -> str:
        return Template("""
$rbiv << Save Picture( "$png_path" , "png");
        """).substitute(**locals())

    @staticmethod
    def jSavePdf(pdf_path, rbiv: str = "rbiv") -> str:
        return Template("""
$rbiv << Save PDF( "$pdf_path");
        """).substitute(**locals())

    @staticmethod
    def jAddWebReport(div_list: List[dict]):
        temp_str = """
Add Report(
{div},
Title( "{title}" ),
Description( "{descript}" )
)
        """
        report_list = []
        for item in div_list:
            report_list.append(
                temp_str.format(
                    div=item["div"],
                    title=item["title"],
                    descript=item["descript"]
                )
            )
        return report_list

    @staticmethod
    def jWebReport(web_reports: list, save_file: str = ""):
        if not save_file:
            save_file = "$TEMP"
        return """
webreport = New Web Report(
    {reports}
);
webreport << Index( Title( "测试数据Web报表" ) );
file = webreport << Save( "{save_file}" );
If( !Is Empty( file ),
    Web( file )
);
        """.format(reports=",".join(web_reports), save_file=save_file)
